package com.ruanjian.service.impl;

import com.ruanjian.dao.GoodsDao;
import com.ruanjian.dao.SaleDao;
import com.ruanjian.execp.NotEnoughException;
import com.ruanjian.po.Goods;
import com.ruanjian.po.Sale;
import com.ruanjian.service.BuyGoodsService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class BuyGoodsServiceImpl implements BuyGoodsService {
    private SaleDao saleDao;
    private GoodsDao goodsDao;

    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }

    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }
//    @Transactional(
//            propagation = Propagation.REQUIRED,
//            isolation = Isolation.DEFAULT,
//            readOnly = false,
//            rollbackFor = {
//                    NullPointerException.class,
//                    NotEnoughException.class
//            }
//    )
    @Transactional
    @Override
    public void buy(int goodsId, int nums) {
        System.out.println("by 方法的开始");
        Sale sale=new Sale();
        sale.setGid(goodsId);
        sale.setNums(nums);
        saleDao.insertSale(sale);
        Goods goods= goodsDao.selectGoods(goodsId);
        if (goods==null){
            throw new NotEnoughException("该商品"+goodsId+"不存在");
        }else if (goods.getAmount()<nums){
            throw new NotEnoughException("该商品"+goodsId+"库存数量不足");
        }
        Goods myGoods=new Goods();
        myGoods.setId(goodsId);
        myGoods.setAmount(nums);
        int num=goodsDao.updateGoods(myGoods);
        System.out.println("by 方法的结束");
    }
}
